package forms;

import org.apache.struts.action.*;

import db.DbConnectionPool;
import db.DbException;

import java.util.*;

import javax.naming.NamingException;
import javax.servlet.http.HttpServletRequest;

import java.sql.*;

public class RegistrationForm extends ActionForm {

	private static final long serialVersionUID = 1L;
	
	private String username = null;
	private String password = null;
	private String repeatPassword = null;
	private String email = null;
	private boolean uErr = false;
	private boolean eErr = false;
	
	// setter/getters
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String pwd) {
		this.password = pwd;
	}
	public String getRepeatPassword() {
		return repeatPassword;
	}
	public void setRepeatPassword(String rpwd) {
		this.repeatPassword = rpwd;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public void reset(ActionMapping mapping, HttpServletRequest request) {
		setUsername(null);
		setPassword(null);
		setRepeatPassword(null);
		setEmail(null);
	}
	
	public void writeDB() {
		Connection conn = null;
		Statement stmt = null;
		ResultSet rs = null;
		PreparedStatement pstmt;

		try {
			conn = DbConnectionPool.getConnection();
			
			// Create the statement
		    stmt = conn.createStatement();
		    	    
		    // make sure the username hasn't already been used
			rs = stmt.executeQuery("SELECT user_name FROM users");
			while( rs.next() ) {
				if ( username.equals(rs.getString("user_name")) ) {
						// do something
				}
			}

			// make sure this user hasn't registered already (email exists)
			rs = stmt.executeQuery("SELECT email FROM users");
			while ( rs.next() ) {
				if ( email.equals(rs.getString("email")) ) {
					// do something
				}
			}
			
			pstmt = conn.prepareStatement("INSERT INTO Users (user_name, password, email) VALUES (?, md5(?), ?)");
	
			pstmt.setString(1, username);
			pstmt.setString(2, password);
			pstmt.setString(3, email);
			pstmt.executeUpdate();
		
			pstmt = conn.prepareStatement("INSERT INTO User_Roles (user_name, role) VALUES (?, ?)");
	
			pstmt.setString(1, username);
			pstmt.setString(2, "student");
			pstmt.executeUpdate();
			
			// close connection
			rs.close();
			stmt.close();
			conn.close();
		} catch (SQLException e) { 
			System.out.println(e);
		} catch (NamingException ex) {
			System.out.println(ex);
		}
	}

}
